package com.web_bloks.widget.client;

import java.util.Enumeration;
import java.util.Vector;

import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.SimplePanel;
import com.web_bloks.storage.client.IRecentList;
import com.web_bloks.storage.client.LocalStorageException;
import com.web_bloks.storage.client.RecentList;
import com.web_bloks.storage.client.RecentListEntry;
import com.web_bloks.storage.client.SimpleRecentList;

/**
 * 
 * @author Jean-Lou Dupont
 *
 */
public class RecentListWidget 
	extends Composite {

	//Constants
	final public static int NUMBER_ENTRIES = 25;
	
	//Storage
	IRecentList liste   = null;
	RecentList gears_rl = null;
	
	//UI
	SimplePanel sp = new SimplePanel();
	ListBox lb = new ListBox();
	
	public RecentListWidget(String tableName) {
		super();
		gears_rl = new RecentList( tableName ); //GEARS
		setup();
	}
	
	public RecentListWidget() {
		super();
		gears_rl = new RecentList(); //GEARS
		setup();
	}//
	
	private void setup() {
		
		sp.add( lb );
		lb.setSize("100%", "100%");
		
		initWidget( sp );
		
		lb.setVisibleItemCount( NUMBER_ENTRIES );
		
		setupStore();
		
		loadView();
		
	}
	
	/**
	 * Try a local database OR revert to just a session based store
	 */
	protected void setupStore() {
		
		if (gears_rl.exists()) {
			
			boolean except = false;
			try {
				gears_rl.initialize();
			} catch (LocalStorageException e) {
				except = true;
			} catch(Exception e) {
				except = true;
			}
			
			if (except)
				liste = new SimpleRecentList();
			else
				liste = gears_rl;
			
			return;
		} 
			
		liste = new SimpleRecentList();
	}//

	/**
	 * Loads the list box
	 */
	protected void loadView() {
		
		Vector<RecentListEntry> l = liste.getLatest( NUMBER_ENTRIES );
		
		if (null==l) return;
		
		Enumeration<RecentListEntry> e = l.elements();
		
		if (null==e) return;
		
		for (int i=0;i<NUMBER_ENTRIES;i++) {
			if (e.hasMoreElements()) {
				RecentListEntry entry = e.nextElement();
				lb.addItem( entry.getEntry() );
			}
		}
		
	}//
	
	/**
	 * Inserts an entry at the top of the list
	 * 
	 * @param entry String
	 * @param meta String
	 */
	public void addEntry(String entry, String meta) {
		liste.insertEntry(entry, meta);
		lb.insertItem( entry, 0 );
	}

	/*****************************************
	 * ChangeListener
	 *****************************************/
	public void addChangeListener(ChangeListener cl) {
		lb.addChangeListener( cl );
	}
	public void removeChangeListener(ChangeListener cl) {
		lb.removeChangeListener( cl );
	}
	public int getSelectedIndex() {
		return lb.getSelectedIndex();
	}
	public String getItemText(int index) {
		return lb.getItemText(index);
	}
	
}//END